//
//  M1HttpNet.m
//  NewMarryU
//
//  Created by apple on 2018/7/16.
//  Copyright © 2018年 Cedar. All rights reserved.
//

#import "M1HttpNet.h"
#import <AdSupport/AdSupport.h>
#import "M1HttpConfig.h"
#import "M1_DES.h"
#import "M1ResponsDecryption.h"
@implementation M1HttpNet
+(NSURLSessionTask *)requestWithMethod:(NSString *)method params:(NSDictionary *)params success:(void(^)(id resDic, NSInteger code, NSString *message))response fail:(void(^)(id resDic, NSInteger code, NSString *message))fail showAni:(BOOL)isShowAni{
    NSMutableDictionary *m1_params = [self m1_defaultParams];
    if (params) {
        [m1_params addEntriesFromDictionary:params];
    }
    if (isShowAni) {
        [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].delegate.window animated:YES];
    }
    return [[AfManager sharedManager] POST:method parameters:m1_params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (isShowAni) {
            [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].delegate.window animated:NO];
        }
        M1ResponsDecryption *dec = [[M1ResponsDecryption alloc]initWithResponse:(NSHTTPURLResponse *)task.response data:responseObject];
        id resData = responseObject;
        if (dec.is_valid) {
            resData = dec.desData;
        }
        if ([resData isKindOfClass:[NSDictionary class]]) {
            resData = [NSJSONSerialization dataWithJSONObject:resData options:0 error:NULL];
        }
    
        NSDictionary *resdic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
        
        id res = resdic[@"items"];
        
        NSInteger code = [[resdic m1_stringKey:@"err"] integerValue];
        
        NSString *msg = [resdic m1_stringKey:@"msg"];
        
        if (code == 0) {
            response(res,code,msg);
        }else{
            fail(res,code,msg);
        }
        if (resdic) {
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:resdic options:NSJSONWritingPrettyPrinted error:nil];
            NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            NSLog(@"--------------%@",jsonStr);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"--------------%@",error);
        if (isShowAni) {
            [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].delegate.window animated:NO];
        }
         fail(nil,error.code,@"网络错误，请稍后重试");
    }];
}

+(NSMutableDictionary *)m1_defaultParams{
    NSMutableDictionary *m1_dic =[ @{
                          @"device":[[UIDevice currentDevice] model],
                          @"system":[NSString stringWithFormat:@"%@ %@",[[UIDevice currentDevice] systemName],[[UIDevice currentDevice] systemVersion]],
                          @"ifa":[[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString],
                          @"app_version":[self m1_appVersion],
                          @"app_id":[self m1_appid]
                          } mutableCopy];
    
    NSString *m1_config = [[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:m1_dic options:0 error:nil] encoding:NSUTF8StringEncoding] stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];
    
    NSMutableCharacterSet *m1_charctSet = [[NSMutableCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
    [m1_charctSet removeCharactersInString:@":#[]@!$&'()*+,;="];
    m1_config = [m1_config stringByAddingPercentEncodingWithAllowedCharacters:m1_charctSet];
    m1_config = [m1_config stringByRemovingPercentEncoding];
    long long timestamp = (long long int) ([[NSDate date] timeIntervalSince1970] * 1000);
    NSString *m1_token = @"i-am-visitor";
    if ([M1User user]) {
        m1_token = [M1User user].token;
    }
    NSMutableDictionary *params = [@{@"configure":m1_config,
                                     @"is_vest":m1_http_is_vest,
                                     @"marry_timestamp":[NSString stringWithFormat:@"%lld", timestamp],
                                     @"version":m1_http_version,
                                     @"token":m1_token,
                                     @"app_version":[self m1_appVersion],
                                     @"app_id":[self m1_appid]
                             } mutableCopy];
    if (![M1User user]) {
        if ([M1SaveTool m1_getGender].length >0) {
            params[@"gender"] = [M1SaveTool m1_getGender];
        }
    }
    
    if ([M1SaveTool m1_Location]) {
        params[@"latitude"] = [M1SaveTool m1_Location][@"lat"];
        params[@"longitude"] = [M1SaveTool m1_Location][@"lon"];
    }
    
    NSString *m1_sign = [NSString stringWithFormat:@"token=%@&sign_key=%@&marry_timestamp=%@",params[@"token"],m1_requst_sign,params[@"marry_timestamp"]] ;
    params[@"marry_sign"] = [[M1_DES m1_md5EncodingStr:m1_sign] lowercaseString];
    
    return params;
    
}
+ (NSString *)m1_appid
{
    return [[NSBundle mainBundle] bundleIdentifier];
}
+ (NSString *)m1_appVersion
{
    NSString *appVersion = [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey];
    return appVersion;
}
@end

@implementation AfManager
+(instancetype)sharedManager{
    static AFHTTPSessionManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[AFHTTPSessionManager alloc]initWithBaseURL:[NSURL URLWithString:m1_base_url]];
        manager.requestSerializer.timeoutInterval = 30;
        AFSecurityPolicy *security = [AFSecurityPolicy defaultPolicy];
        security.validatesDomainName = YES;
        manager.securityPolicy = security;
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes =[[NSSet alloc] initWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    });
    return (AfManager *)manager;
}
@end
